package dbconnector;

import java.util.Arrays;

import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceRegistration;

import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.Mongo;
import com.mongodb.ServerAddress;
import com.mongodb.WriteConcern;

import dbconnector.impl.ServiceRegisterManager;
import dbconnector.service.IServiceRegisterManager;

public class Activator implements BundleActivator {

	private static BundleContext context;
	private final String DB_NAME = "mydb";
	private final String DESCRIPTOR_NAME = "bundles";

	private DBCollection coll;
	private Mongo mongo;

	ServiceRegistration<?> serviceRegistration;

	static BundleContext getContext() {
		return context;
	}

	public void start(BundleContext bundleContext) throws Exception {
		Activator.context = bundleContext;
		mongo = new Mongo(Arrays.asList(new ServerAddress("149.156.205.146", 27017), new ServerAddress(
				"149.156.205.149", 27017), new ServerAddress("149.156.205.150", 27017), new ServerAddress(
				"149.156.205.151", 27017), new ServerAddress("149.156.205.152", 27017), new ServerAddress(
				"149.156.205.153", 27017)));

		DB db = mongo.getDB(DB_NAME);
		mongo.setWriteConcern(WriteConcern.SAFE);
		coll = db.getCollection(DESCRIPTOR_NAME);

		ServiceRegisterManager serviceRegisterManager = new ServiceRegisterManager(coll);
		serviceRegistration = context.registerService(IServiceRegisterManager.class.getName(), serviceRegisterManager,
				null);
	}

	public void stop(BundleContext bundleContext) throws Exception {
		Activator.context = null;
		serviceRegistration.unregister();
		mongo.close();
	}

}
